import code
import uuid

from django.core.cache import cache
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from base.models import User, LocationHistory, UserInfo
from base.serializers import RegisterSerializer, FeedbackSerializer, LocationHistorySerializer, UserInfoSerializer, \
    SearchUserInfoSerializer
from base.tasks import email_verify_code
from utils.auth import create_token
from utils.send_email import send_email


# Create your views here.
class RegisterView(APIView):
    """
    用户注册
    """
    authentication_classes = []
    def post(self,request):
        email=request.data.get('email')
        emailCode=request.data.get('emailCode')
        if email:
            code=cache.get(email)
            if code==emailCode:
                uid=uuid.uuid4()
                data=request.data
                data['uid']=str(uid)
                serializer = RegisterSerializer(data=data)
                if serializer.is_valid():
                    serializer.save()
                    return Response(data={'msg':'注册成功','code':200})
                else:
                    return Response(data={'msg':'注册失败','error':serializer.errors,'code':409})
            elif code is None:
                return Response(data={'msg':'注册失败','error':'邮箱验证码过期','code':406})
            else:
                return Response(data={'msg':'注册失败','error':'邮箱验证码错误','code':405})
        else:
            return Response(data={'msg':'注册失败','error':'邮箱验证码不能为空','code':404})


class LoginView(APIView):
    """
    用户登录
    """
    authentication_classes = []
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        user=User.objects.filter(username=username,is_delete=False).first()
        if user:
            check_user=User.objects.filter(username=username,password=password).first()
            if check_user:
                payload={
                    'username':check_user.username,
                    'email':check_user.email,
                    'phone':check_user.phone,
                    'role':check_user.role,
                }
                token=create_token(payload)
                return Response(data={'msg':'登录成功','data':token,'code':200})
            else:
                return Response(data={'msg':'登录失败','error':'密码错误','code':402})
        else:
            return Response(data={'msg':'登陆失败','error':'用户不存在','code':401})


class PwdView(APIView):
    """
    post:修改密码
    """
    authentication_classes = []
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('oldPassword')
        user=User.objects.filter(username=username).first()
        if user:
            user=User.objects.filter(username=username,password=password).first()
            if user:
                serializer=RegisterSerializer(instance=user,data=request.data,partial=True)
                if serializer.is_valid():
                    serializer.save()
                    return Response(data={'msg':'修改成功','code':200})
                else:
                    return Response(data={'msg':'修改失败','error':serializer.errors,'code':409})
            else:
                return Response(data={'msg':'修改失败','error':'旧密码错误','code':402})
        else:
            return Response(data={'msg':'修改失败','error':'用户名不存在','code':401})


class FindPwdView(APIView):
    """
    post:找回密码
    """
    authentication_classes = []
    def post(self,request):
        email=request.data.get('email')
        code=cache.get(email)
        verify_code=request.data.get('code')
        if code:
            if code==verify_code:
                user=User.objects.filter(username=request.data.get('username')).first()
                if user:
                    serializer=RegisterSerializer(instance=user,data=request.data,partial=True)
                    if serializer.is_valid():
                        serializer.save()
                        return Response(data={'msg':'修改成功','code':200})
                    else:
                        return Response(data={'msg': '修改失败', 'error': serializer.errors, 'code': 409})
                else:
                    return Response(data={'msg':'修改失败','error':'用户名不存在','code':401})
            else:
                return Response(data={'msg':'修改失败','error':'邮箱验证码错误','code':405})
        else:
            return Response(data={'msg':'修改失败','error':'邮箱验证码不能为空','code':404})


class SendEmailView(APIView):
    """
    get:发送邮箱验证码
    """
    authentication_classes = []
    def post(self,request):
        email_account=request.data.get('email')
        if email_account:
            try:
                res=email_verify_code.delay(email_account)
                print(res)
                return Response(data={'msg': '发送成功', 'code': 200})
            except Exception as e:
                return Response(data={'msg':'发送失败','error':str(e),'code':500})
        else:
            return Response(data={'msg':'发送失败','error':'邮箱不能为空','code':401})

class FeedbackView(APIView):
    """
    post:反馈内容
    """
    authentication_classes = []
    def post(self,request):
        serializer=FeedbackSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data={'msg':'反馈成功','code':200})
        else:
            return Response(data={'msg':'反馈失败','error':serializer.errors,'code':408})

class LocationHistoryView(APIView):
    """
    post:定位记录
    """
    authentication_classes = []
    def post(self,request):
        serializer=LocationHistorySerializer(data=request.data,partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data={'msg':'添加成功','code':200})
        else:
            return Response(data={'msg':'添加失败','error':serializer.errors,'code':408})

    def get(self,request):
        username=request.query_params.get('username')
        submit_time=request.query_params.get('submit_time')
        if username:
            if submit_time:
                year, month, day = submit_time.split('-')
                Locations=LocationHistory.objects.filter(username=username,submit_time__year=year,
                                                         submit_time__month=month,submit_time__day=day).order_by('-submit_time').all()
            else:
                Locations = LocationHistory.objects.filter(username=username).order_by('-submit_time').all()
            page = PageNumberPagination()
            page.page_size = 15
            page.max_page_size = 50
            page.page_query_param = 'page'
            page.page_size_query_param = 'size'
            Location_data = page.paginate_queryset(queryset=Locations, request=request)
            serializer=LocationHistorySerializer(instance=Location_data,many=True)
            return Response(data={'msg':'查询成功','data':serializer.data,'code':200})
        else:
            return Response(data={'msg':'查询失败','error':'用户名不能为空','code':401})

class UserInfoView(APIView):
    authentication_classes = []
    def get(self,request):
        username=request.query_params.get('username')
        if username:
            userInfo=UserInfo.objects.filter(username=username).first()
            serializer=SearchUserInfoSerializer(instance=userInfo)
            return Response(data={'msg':'查询成功','data':serializer.data,'code':200})
        else:
            return Response(data={'msg':'查询失败','error':'用户名不能为空','code':401})
    def post(self,request):
        username=request.data.get('username')
        if username:
            userInfo=UserInfo.objects.filter(username=username).first()
            serializer=None
            if userInfo:
                serializer=UserInfoSerializer(instance=userInfo,data=request.data,partial=True)
            else:
                serializer=UserInfoSerializer(data=request.data,partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(data={'msg':'修改成功','code':200})
            else:
                return Response(data={'msg':'修改失败','error':serializer.errors,'code':409})
        else:
            return Response(data={'msg':'修改失败','error':'用户名不能为空','code':401})
